import $ from 'jquery'
import Load from '@/utils/Load.js'
import Utils from '@/utils/Utils.js'
// import ModalApi from '@/components/SwModal/api.js'

global.openResult = false
global.openRealTrendResult = true
global.openKLinesDataResult = true
global.openOrderStatusResult = true
global.openDealResult = true
global.openOrderBookResult = true
global.openTradesResult = true
global.openSendOrderResult = true
global.openAssetsChangedResult = true
global.params = null
global.timer = null
global.timeout = null
global.TradingData = []

// 等待JoinGroup 成功回调success, 才显示实时交易与K线
// 等待JoinGroup 成功回调success, 才能调用SetDisplayPrecision
// 等待回待SetDisplayPrecision为success，才显示orderbook
let realtimePush = {
  userId: '',
  pairId: '',
  oldPairId: '',
  MarriedDealHub: null,
  isInited: false,
  params: null,
  isJoinGroupSuccessful: false,
  isSwitchPrecisionSuccessful: false,
  onReady () { },
  init (params) {
    global.params = params
    this.params = params
    this.api = params.address + '/signalr/hubs'
    this.js = params.address + '/signalr/js'
    this.oldUserId = this.userId // 旧userId
    this.userId = params.userId
    this.pairId = params.pairId
    this.onReady = params.onReady
    // console.log(this.api, this.js)
    // if (this.isInited) { 首页使用了相同的实例，返回这里restart会报connect before can send data，暂时没搞懂
    //   // if (this.oldUserId !== this.userId) {
    //   //   // this.restart()
    //   //   location.reload()
    //   // } else {
    //   //   this.switchPair(this.pairId)
    //   // }
    //   this.restart()
    // } else {}
    Load(this.js, () => {
      this.MarriedDealHub = $.connection.ExchangesHub

      $.connection.hub.error(function (error) {
        // console.log('SignalR error: ' + error)
      })

      $.connection.hub.connectionSlow(function () {
        // console.log('connectionSlow')
      })

      $.connection.hub.reconnecting(function () {
        // console.log('reconnecting')
      })

      $.connection.hub.stateChanged(function (change) {
        if (change.newState === $.signalR.connectionState.reconnecting) {
          // console.log('Re-connecting')
        } else if (change.newState === $.signalR.connectionState.connected) {
          // console.log('The server is online')
        }
      })
      // 重新持续连接
      $.connection.hub.disconnected(function () {
        // console.log('disconnected')
        setTimeout(function () {
          this.addCallback && this.addCallback(this.MarriedDealHub) // 重新定义，防止被覆盖
          this.start().then(() => {
            this.switchPair(this.pairId)
          })
        }, 5000) // 5s后重新启动连接
      })

      this.addCallback(this.MarriedDealHub)
      this.start().then((res) => {
        this.switchPair(this.pairId)
        this.isInited = true
      })
    })

    // 离开页面要关闭
    global.window.addEventListener('beforeunload', this.stop)
    global.window.addEventListener('unload', this.stop)
  },
  start () {
    let p = Utils.makePromise()
    $.connection.hub.url = this.api
    $.connection.hub.logging = true
    $.connection.hub.qs = 'UserID=' + this.userId + '&' + 'GroupID=' + this.pairId
    $.connection.hub.start({ transport: 'auto' }).done((res) => {
      // console.log('start done')
      p.resolveHandle(res)
    }).fail((res) => {
      p.rejectHandle(res)
      // console.log('start fail')
    })
    return p
  },
  restart (params) {
    console.log('restart')
    $.connection.hub.stop()

    this.addCallback(this.MarriedDealHub) // 重新定义，防止被覆盖
    this.start().then(() => {
      this.switchPair(this.pairId)
    })
  },
  switchPair (pairId) {
    global.timeout && clearTimeout(global.timeout)
    global.timeout = null
    global.timer && clearInterval(global.timer)
    global.timer = null

    this.pairId = pairId
    this.isSwitchPrecisionSuccessful = false // 切换交易对，只有等加组成功后才能接收推过来的委托列表，不然会接收到旧的
    this.updateGroup(this.pairId, this.oldPairId || '').then(() => {
      this.oldPairId = this.pairId
      this.onReady()
    })
  },
  stop () {
    // console.log('stop')
    global.hasTime = 0
    global.timeout && clearTimeout(global.timeout)
    global.timeout = null
    global.timer && clearInterval(global.timer)
    global.timer = null
    $.connection.hub.stop()
  },
  updateGroup: (pairId, oldPairId) => {
    realtimePush.isJoinGroupSuccessful = false
    let p = Utils.makePromise()
    // console.log('添加了新', pairId)
    // 这里不能用this，得到的是{a: object}
    try {
      realtimePush.MarriedDealHub.server.joinGroup(pairId, oldPairId).done((result) => {
        // console.log('joinGroup', 'pairId:', pairId, 'oldPairId:', oldPairId, result)
        if (result !== 'success') return
        realtimePush.isJoinGroupSuccessful = true
        p.resolveHandle(result)
      })
    } catch (e) {
      // console.log(e)
    }
    return p
  },
  addCallback (MarriedDealHub) {
    // 交易对信息更新
    MarriedDealHub.client.RealTrendCallback = (result) => {
      global.openResult && global.openRealTrendResult && console.log('交易对信息推送RealTrendCallback', result)
      Utils.isFunction(this.params.RealTrendCallback) && this.params.RealTrendCallback(Utils.copyObject(result))
    }

    // k线
    MarriedDealHub.client.KLinesDataCallback = (result) => {
      global.openResult && global.openKLinesDataResult && console.log('推送k线KLinesDataCallback', result)
      Utils.isFunction(this.params.KLinesDataCallback) &&
      this.isJoinGroupSuccessful &&
      this.params.KLinesDataCallback(Utils.copyObject(result)) // 避免vue改变数据源为响应式
    }

    // 用户的挂单列表，分为正在挂的单和历史单
    MarriedDealHub.client.OrderStatusCallback = (result) => { // 订单状态 =>变更
      global.openResult && global.openOrderStatusResult && console.log('推送用户的当前委托和历史订单OrderStatusCallback', result) //
      Utils.isFunction(this.params.OrderStatusCallback) && this.params.OrderStatusCallback(Utils.copyObject(result))
    }

    // 成交记录
    MarriedDealHub.client.DealCallback = (result) => {
      global.openResult && global.openDealResult && console.log('推送用户的成交记录DealCallback', result) //
      Utils.isFunction(this.params.DealCallback) && this.params.DealCallback(Utils.copyObject(result))
    }

    // 委托列表
    MarriedDealHub.client.OrderBookCallback = (result) => { // OrderBo =>ok
      global.openResult && global.openOrderBookResult && console.log('推送委托列表OrderBookCallback', result) //
      Utils.isFunction(this.params.OrderBookCallback) &&
      this.isSwitchPrecisionSuccessful &&
      this.params.OrderBookCallback(Utils.copyObject(result))
    }

    // 交易历史
    MarriedDealHub.client.TradesCallback = (result) => { // 最新成 =>交单
      global.openResult && global.openTradesResult && console.log('推送交易历史TradesCallback', result) //
      Utils.isFunction(this.params.TradesCallback) &&
      this.isJoinGroupSuccessful &&
      this.params.TradesCallback(Utils.copyObject(result))
    }

    // 下单提示
    MarriedDealHub.client.SendOrderResult = (result) => {
      global.openResult && global.openSendOrderResult && console.log('下单提示SendOrderResult', result) //
      Utils.isFunction(this.params.SendOrderResult) && this.params.SendOrderResult(Utils.copyObject(result))
    }

    // 用户持仓
    MarriedDealHub.client.AssetsChangedCallback = (result) => { // 资金持仓 =>变更
      global.openResult && global.openAssetsChangedResult && console.log('推送用户持仓AssetsChangedCallback', result) //
      Utils.isFunction(this.params.AssetsChangedCallback) && this.params.AssetsChangedCallback(Utils.copyObject(result))
    }
  },
  switchPrecision (pairId, precision) {
    this.isSwitchPrecisionSuccessful = false
    global.openResult && console.log('改变精度setDisplayPrecision', pairId, precision)
    this.MarriedDealHub.server.setDisplayPrecision(pairId, precision).done((result) => {
      // console.log('setDisplayPrecision', pairId, precision, result)
      if (result !== 'success') return
      this.isSwitchPrecisionSuccessful = true
    })
  }
}

export default realtimePush
